#!/bin/bash
function install_docker() {
    echo -e "${blue}当前正在执行的操作为:${nocolor} ${green}安装Docker${nocolor}"
    echo ""
    if [ "$system_ver" != "7" ];then
        echo -e "$Error 不支持的操作系统版本！\n系统要求CentOS7 x86_64/amd64/ARM64/AARCH64"
        anykeyback
        return 1
    fi
    installd_docker_ver=$(rpm -q docker-ce 2>/dev/null|awk -F"-" '{print $3}')
    if [ -n "$installd_docker_ver" ];then
        echo -ne "$Warn 系统已经安装docker-ce $installd_docker_ver，继续安装，现有版本将被卸载
继续[Yy,Enter],退出[Nn]: "
        read isYn
        [[ $isYn != [Nn] ]] || { sleep 0.5;return 1; }
        echo ""
    fi

    dockerVer=
    
    while [[ ! ${dockerVer_digit} =~ ^[0-9]+$ || "$dockerVer_dot" == "0" || "$dockerVer_endwith" == "." ]]
    do
        echo -ne "输入要安装的Docker版本[默认最新版本], 列出版本Hh[行数]: "
        read dockerVer
        dockerVer=${dockerVer:-9999.9999}
        dockerVer=`echo $dockerVer`
        dockerVer_digit=${dockerVer//./}
        dockerVer_digit=${dockerVer_digit//-/}
        dockerVer_dot=$(echo $dockerVer|grep -o "\."|wc -l)
        dockerVer_endwith=${dockerVer:0-1}
        dockerVer_=${dockerVer^^}
        if [[ ${dockerVer_} =~ H[0-9]*$ ]];then
            if [ "$die_network" == "ture" ];then
                    echo -e "$Info 设备未联网，不支持查询"
            else
                show_lines=$(echo $dockerVer|egrep -o "[0-9]*"|head -n1)
                if [ "X$show_lines" == "X" ];then
                    show_lines=10
                fi
                curl -so $workHome/logs/docker.xml https://mirrors.aliyun.com/docker-ce/linux/centos/${system_ver}/x86_64/stable/Packages/
                cat $workHome/logs/docker.xml|tr -d "\r"|egrep -o ">docker-ce-[0-9.]+.*\.x86_64\.rpm"|sort -ruV|awk -F'-ce-' '{print $2}'|awk -F".el" '{print $1}'|head -n $show_lines
            fi
        else
            if [[ ! ${dockerVer_digit} =~ ^[0-9]+$ || "$dockerVer_dot" == "0" || "$dockerVer_endwith" == "." ]];then
                echo -e "$Warn docker版本号只能由数字、-以及.组成，且不以.结尾，请重新输入！"
                sleep 0.5
            fi    
        fi
    done
    echo ""
    
    if [ "${dockerVer}" == "9999.9999" ];then
        dockerVer=
    fi
    dockerVer=`echo $dockerVer`
    dockerHome="$workHome/packages/docker"
    main_dockerVer=${dockerVer%.*}
    main_dockerVer_=${dockerVer%%.*}

    echo -e "${cyan}将开始Docker安装过程${nocolor}"
    echo ""
    echo ""
    echo -e "$Info ${purple}检查并卸载已有docker-ce环境${nocolor}"
    yum remove -y docker-ce docker-ce-cli docker docker-client docker-client-latest docker-common docker-latest docker-latest-logrotate docker-logrotate docker-engine containerd.io container-selinux docker-ce-selinux

    echo -e "$Info ${purple}添加Docker-ce YUM源${nocolor}"
    cat /etc/yum.repos.d/docker-ce.repo 2>/dev/null|grep -E "aliyun.com|tsinghua.edu.cn" >/dev/null 2>&1
    if [ "$?" != "0" ];then
        curl --progress-bar --fail --connect-timeout 30 -o /etc/yum.repos.d/docker-ce.repo https://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo
        if [ "$?" != "0" ];then
          curl --progress-bar --fail --connect-timeout 30 -o /etc/yum.repos.d/docker-ce.repo https://download.docker.com/linux/centos/docker-ce.repo
          sed -i 's+download.docker.com+mirrors.tuna.tsinghua.edu.cn/docker-ce+' /etc/yum.repos.d/docker-ce.repo
        fi
    fi
    
    dockerVer_newest=`yum list docker-ce --show-duplicates 2>/dev/null|grep docker-ce.x86_64|sort -n|tail -n1|awk '{print $2}'|awk -F":" '{print $2}'|awk -F"-" '{print $1}'`
    if [ -n "$dockerVer_newest" -a -z "$dockerVer" ];then
        dockerVer_=$dockerVer_newest
    elif [ -z "$dockerVer_newest" -a -z "$dockerVer" ];then
        dockerVer_="errror"
    fi
    
    offPack=`ls $dockerHome 2>/dev/null|grep "$dockerVer_"|grep docker-ce|grep -v cli|grep ".rpm"`
    if [ -n "$offPack" ];then
        echo -e "$Info ${purple}检测到离线安装包，尝试离线安装${nocolor}"
        all_offPack=`ls $dockerHome 2>/dev/null|grep "$dockerVer_"|grep ".rpm"`
        
        if [ "$main_dockerVer" != "17.03" ];then
           install_command="yum localinstall -y --setopt=obsoletes=0 $dockerHome/$all_offPack $dockerHome/container*.rpm"
        else
           install_command="yum localinstall -y --setopt=obsoletes=0 $dockerHome/$all_offPack"
        fi
        $install_command
    else
        errrrrrrrr>/dev/null 2>&1
    fi
    
    if [ "$?" != "0" ];then
        echo -e "$Info ${purple}尝试使用在线安装${nocolor}"
        if [ -z "$dockerVer" ];then
          yum -y --setopt=obsoletes=0 install docker-ce
        else
          yum -y --setopt=obsoletes=0 install docker-ce-$dockerVer* docker-ce-cli-$dockerVer* 
        fi
        if [ "$?" != "0" ];then
          echo -e "$Error 安装失败，退出！"
          anykeyback
          return 1
        fi
    fi
    
    echo -e "$Info ${purple}启动docker${nocolor}"
    systemctl start docker
    
    echo -e "$Info ${purple}配置docker镜像加速${nocolor}"

    cat > /etc/docker/daemon.json <<EOF
{
    "registry-mirrors": ["https://r9tuk62b.mirror.aliyuncs.com", "https://docker.mirrors.ustc.edu.cn"],
    "exec-opts": ["native.cgroupdriver=systemd"],
    "log-driver": "json-file",
    "log-opts": {
    "max-file": "3",    
    "max-size": "100m"
    },
    "storage-driver": "overlay2",
    "storage-opts": [
      "overlay2.override_kernel_check=true"
    ]
}
EOF
    echo -e "$Info ${purple}重启docker并设置docker随机启动${nocolor}"
    systemctl restart docker
    systemctl enable docker >/dev/null 2>&1

    echo -e "$Info ${purple}安装docker-compose，非必要安装${nocolor}"
    composeName="docker-compose-`uname -s`-`uname -m`"
    docker_compose=`ls $dockerHome 2>/dev/null|grep "$composeName"`
    if [ -n "$docker_compose" ];then
        /bin/cp -f $dockerHome/$docker_compose /usr/local/bin/docker-compose
        chmod +x /usr/local/bin/docker-compose
    else
        cd $dockerHome
        newest_ver=`git ls-remote --tags https://github.com/docker/compose.git 2>/dev/null|awk -F"/" '{print $3}'|egrep -v "docs|rc|test" |grep -v "v"|sort -rV|head -n1`
        newest_ver=${newest_ver:-1.25.5}
        curl --progress-bar --connect-timeout 30 -m 360 --fail -L -O https://get.daocloud.io/docker/compose/releases/download/$newest_ver/docker-compose-`uname -s`-`uname -m` >>$logs_file 2>&1
        if [ "$?" == "0" ];then
          /bin/cp -f docker-compose-`uname -s`-`uname -m` /usr/local/bin/docker-compose
          chmod +x /usr/local/bin/docker-compose
        else
          rm -rf docker-compose-`uname -s`-`uname -m`
        fi
    fi
    
    echo ""
    #判断是否安装成功
    dockerPid=`pidof dockerd`
    docker_compose_ver=`docker-compose -v 2>/dev/null|awk '{print $3}'|sed 's/,//g'`
    docker_ver=`docker -v 2>/dev/null|grep -Eo "[0-9]+\.[0-9]+\.[0-9]+"`
    
    if [ -n "$dockerPid" -a -n "$docker_compose_ver" ];then
        echo -e "$Info ${light_green}Dcoker $docker_ver以及docker-compose $docker_compose_ver安装成功！${nocolor}"
    elif [ -n "$dockerPid" -a -z "$docker_compose_ver" ];then
        echo -e "$Info ${light_green}Dcoker $docker_ver安装成功，但是docker-compose安装失败，不影响docker使用！${nocolor}"
    elif [ -z "$dockerPid" -a -n "$docker_compose_ver" ];then
        echo -e "$Error Dcoker ${docker_ver}安装失败，docker-compose $docker_compose_ver安装成功！"
    else
        echo -e "$Error Dcoker $docker_ver及docker-compose安装失败！"
    fi
    anykeyback
}
